package com.ort.ezcalendar.rest;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.ort.ezcalendar.rest.ResponseListener.EnumResponse;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
import android.os.AsyncTask;

public class ValidateUserTask extends AsyncTask<String, Void, String> {
	private ProgressDialog dialog;
	protected Context applicationContext;
	private ResponseListener listener;

	public ValidateUserTask(ResponseListener l, Context c) {
		listener = l;
		applicationContext = c;
		dialog = new ProgressDialog(applicationContext);
	}

	@Override
	protected void onPreExecute() {

		this.dialog = ProgressDialog.show(applicationContext,
				"Conectando", "Validando usuario...", true);
	}

	@Override
	protected String doInBackground(String... params) {
		try {
			String urlConection = "http://192.168.2.4/EzCalendar/ServiceEzCalendar.svc/ValidateUser/"
					+ params[0] + "/" + params[1];
//			"+ readProperties("connection") + readProperties("validate_user")
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(urlConection);
			
			httpGet.setHeader("content-type", "application/json");

			HttpResponse httpResponse = httpClient.execute(httpGet);

			HttpEntity httpEntity = httpResponse.getEntity();
			String stringResponse = EntityUtils.toString(httpEntity);
			JSONObject jsonOnject = new JSONObject(stringResponse);
			 
	        if (jsonOnject.getBoolean("response")){
				return EnumResponse.TRUE.toString();
	        } else {
	        	return EnumResponse.FALSE.toString();
	        }
	        
		} catch (NotFoundException e) {
			return EnumResponse.ERROR_CONECTION.toString();
		} catch (Exception e) {
			return EnumResponse.ERROR_CONECTION.toString();
		}
	}

	@Override
	protected void onPostExecute(String result) {
		this.dialog.cancel();
		listener.fireResponse(EnumResponse.valueOf(result));
	}
	
	private String readProperties(String key) throws IOException {
		String value = "";
		try {
			Resources resources = applicationContext.getResources();
			AssetManager assetManager = resources.getAssets();
			InputStream inputStream = null;
			inputStream = assetManager.open("conection.properties");
			Properties properties = new Properties();
			properties.load(inputStream);
			value = properties.getProperty(key);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return value;
	}

}
